def manhattan_distance(state, goal_state):
distance = 0
for i in range(len(state)):
for j in range(len(state[0])):
value = state[i][j]
if value != 0: 忽略空格
goal_i, goal_j = divmod(value 1, len(state[0]))
distance += abs(i goal_i) + abs(j goal_j)
return distance
while open_list:
_, current_state = heapq.heappop(open_list)
if current_state == goal_state:
break
产生下一个状态
for next_state in get_next_states(current_state):
new_cost = cost_so_far[tuple(map(tuple, current_state))] + 1
if tuple(map(tuple, next_state)) not in cost_so_far or new_cost < cost_so_far[tuple(map(tuple, next_state))]:
cost_so_far[tuple(map(tuple, next_state))] = new_cost
priority = new_cost + manhattan_distance(next_state, goal_state)
heapq.heappush(open_list, (priority, next_state))
came_from[tuple(map(tuple, next_state))] = current_state
重建路径
if goal_state not in came_from:
return None
current = goal_state
path = []
while current != initial_state:
path.append(current)
current = came_from[tuple(map(tuple, current))]
path.append(initial_state)
path.reverse()
return path
def get_next_states(state):
实现状态转移,空白方块移动
next_states = []
找到空白方块的位置
zero_i, zero_j = None, None
for i in range(len(state)):
for j in range(len(state[0])):
if state[i][j] == 0:
zero_i, zero_j = i, j
break
if zero_i is not None:
break
上下左右移动
directions = [(0, 1), (0, 1), (1, 0), (1, 0)]
for dx, dy in directions:
new_i, new_j = zero_i + dx, zero_j + dy
if 0 <= new_i < len(state) and 0 <= new_j < len(state[0]):
new_state = [row[:] for row in state]
new_state[zero_i][zero_j], new_state[new_i][new_j] = new_state[new_i][new_j], new_state[zero_i][zero_j]
next_states.append(new_state)
return next_states